const Config = require('@/config/index.js');

const CryptoJS = require('./crypto-js.js'); //加密

function encrypted(param, key = 'c922b15a7f3562a5', iv = '9512741612342671') {
    // key 和 iv 可以一致
    key = CryptoJS.enc.Utf8.parse(key);
    iv = CryptoJS.enc.Utf8.parse(iv);
    var encrypted = CryptoJS.AES.encrypt(param, key, {
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    });
    encrypted = encrypted.toString();
    return encrypted;
} //解密

function decrypted(param, key = 'c922b15a7f3562a5', iv = '9512741612342671') {
    // key 和 iv 可以一致
    key = CryptoJS.enc.Utf8.parse(key);
    iv = CryptoJS.enc.Utf8.parse(iv);
    var decrypted = CryptoJS.AES.decrypt(param, key, {
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    });
    decrypted = CryptoJS.enc.Utf8.stringify(decrypted);
    return decrypted;
}
/**
 * 检测是否为空
 */

const isEmpty = (str) => {
    if (str == '' || str == null || typeof str == 'undefined') {
        return true;
    }

    return false;
};
/**
 * 控制台打印
 */

const print = (str) => {
    if (Config.debug) {
        console.log(str);
    }
};
/**
 * 强制保留两位小数
 */

const toDecimal = (num) => {
    var result = parseFloat(num);

    if (isNaN(result)) {
        return false;
    }

    result = Math.round(num * 100) / 100;
    var s_x = result.toString();
    var pos_decimal = s_x.indexOf('.');

    if (pos_decimal < 0) {
        pos_decimal = s_x.length;
        s_x += '.';
    }

    while (s_x.length <= pos_decimal + 2) {
        s_x += '0';
    }

    return s_x;
};
/**
 * 检查版本更新
 */

const checkUpdate = () => {
    const updateManager = uni.getUpdateManager();
    updateManager.onCheckForUpdate(function (res) {
        if (res.hasUpdate) {
            updateManager.onUpdateReady(function () {
                uni.showModal({
                    title: '更新提示',
                    content: '新版本已经准备好，是否重启应用？',
                    success: function (res) {
                        if (res.confirm) {
                            updateManager.applyUpdate();
                        }
                    }
                });
            });
            updateManager.onUpdateFailed(function () {
                uni.showModal({
                    title: '升级失败',
                    content: '新版本下载失败，请检查网络！',
                    showCancel: false
                });
            });
        }
    });
};

module.exports = {
    encrypted,
    decrypted,
    isEmpty,
    print,
    toDecimal,
    checkUpdate
};
